/**
 * @file fileTransferCmds.c
 * @author MTF-1
 *
 * @date 14-01-2011 DD-MM-YYYY
 * @version 0.3
 *
 * @section DESCRIPTION
 *
 * Module for file transfer commands.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "fileTransferCmds.h"
#include "connectionCmds.h"

#define ERROR 1
#define NOERROR 0

/**
 * Upload file to server.
 *
 * @author Rik Janssen, Robbert Busser
 */
int cmdUpload(char *ptr_sFilenameClient, char *ptr_sFilenameServer)
{
    int inFileFD = 0, n = 0;
    char buf[100];
    char sRecvBuf[100];
    char sUploadCmd[200] = "UPLOAD ";
    int i;

    for(i = 0; i < 100; i++)
    {
        buf[i] = 0;
        sRecvBuf[i] = 0;
    }

    strcat(sUploadCmd, ptr_sFilenameServer);
    send(iSocketFD, sUploadCmd, strlen(sUploadCmd)+1, 0);
    recv(iSocketFD, &sRecvBuf, 100, 0);

    if(!strcasecmp(sRecvBuf, "READY")) {
        printf("Opening file: %s\n", ptr_sFilenameClient);
        if((inFileFD = open(ptr_sFilenameClient, O_RDONLY)) == -1)
            perror("can't open file\n");
        else {
            printf("Reading and uploading file...\n");

            while((n = read(inFileFD, &buf, 100)) > 0)
                send(iSocketFD, buf, 100, 0);

            close(inFileFD);
            if(n == -1)
                fprintf(stderr, "read error on file\n");
            else {
                printf("Done!\n");
                return NOERROR;
            }
        }
    }
    return ERROR; //geen goede reactie van server of cant read file
}

/**
 * Download file from server.
 * 
 * @author Rik Janssen
 */
int cmdDownload(char *ptr_sFilenameServer, char *ptr_sFilenameClient)
{
    int outFileFD = 0, n = 0;
    char buf[100];
    char sDownloadCmd[200] = "DOWNLOAD ";
    int i;

    for(i = 0; i < 100; i++)
    {
        buf[i] = 0;
    }

    /*Send DOWNLOAD cmd*/
    strcat(sDownloadCmd, ptr_sFilenameServer);
    send(iSocketFD, sDownloadCmd, strlen(sDownloadCmd)+1, 0);

    /*Open or creat file*/
    printf("Creating/Opening file: %s\n", ptr_sFilenameClient);
    if((outFileFD = open(ptr_sFilenameClient, O_WRONLY|O_CREAT, 0644)) == -1) {
        send(iSocketFD, "ERROR", 6, 0);
        perror("error opening or creating file\n");
    }
    else {
        send(iSocketFD, "READY", 6, 0);

        //server data inlezen en wegschrijven
        while((n = recv(iSocketFD, &buf, 100, 0)) > 0) {
            if(write(outFileFD, &buf, n) != n) {
                perror("write error on destination file\n");
            }
        }

        close(outFileFD);
        if(n == -1)
            fprintf(stderr, "download error\n");
        else {
            printf("Done!\n");
            return NOERROR;
        }
    }

    return ERROR; //geen goede reactie van server of error creating file
}
